package com.muapet.util;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.muapet.model.Admin;
import com.muapet.util.constants.MyConstants;

public class PrivFiler implements Filter {

	/**
	 * 不限制路径
	 */
	Set<String> ACCESS_PRIVILEGES = new HashSet<String>();

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("unchecked")
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		Admin loginAdmin = (Admin) request.getSession().getAttribute(
				"loginAdmin");
		String uri = request.getRequestURI();
		if (ACCESS_PRIVILEGES.contains(uri)) {
			chain.doFilter(request, response);
		} else {
			if (loginAdmin == null) {
				request.setAttribute("msg", "您没有权限");
				request.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(
						request, response);
			} else if (loginAdmin.getId() == 1) {// 根用户不做判断
				chain.doFilter(request, response);
			} else {
				Set<String> privileges = (Set<String>) request.getSession()
						.getAttribute("privileges");
				if (privileges.contains(uri)) {
					chain.doFilter(request, response);
				} else {
					request.setAttribute("msg", "您没有权限");
					request.getRequestDispatcher("/WEB-INF/jsp/error.jsp")
							.forward(request, response);
				}
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		ACCESS_PRIVILEGES.add(MyConstants.BASE_URL + "admin/login.do");
		ACCESS_PRIVILEGES.add(MyConstants.BASE_URL + "admin/logout.do");
	}

}
